package com.notify.paynotify.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@RestController
@RequestMapping(value = "/notify")
public class NotifyController {

    private Logger logger = LoggerFactory.getLogger(NotifyController.class);

    @RequestMapping(value = "/callback")
    public String callback(HttpServletRequest request, HttpServletResponse response) {
        String res = "";
        try {
            String method = request.getMethod();
            logger.info("请求方式：{}", method);
            logger.info("请求地址：{}", request.getRemoteAddr());
            res = read(request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return res;
    }


    public String read(HttpServletRequest request) {
        InputStream is = null;
        BufferedReader reader = null;
        try {
            is = request.getInputStream();
            //将InputStream转换成String
            reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            String resXml = sb.toString();
            logger.info("数据源：\n{}", resXml);
            return resXml.trim();
        } catch (Exception e) {
            logger.error("{}", e);
        } finally {
            try {
                is.close();
                reader.close();
            } catch (IOException e) {

            }
        }
        return null;
    }

}
